package cn.xuqiudong.sso.shiro;

import java.util.Collection;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * REDIS缓存 
 * @author VIC.xu
 * 备注: 本方法不要打log日志,因为本项目重写了日志布局会获取当前用户信息,从而致使循环调用(此处调用日志布局-->日志布局调用此处session)
 *
 */
public class RedisCache<K, V> implements Cache<K, V> {

	private String							cacheName;

	private static final String				DEFAULT_CACHE_NAME	= "shiro-activeSessionCache";

	private HashOperations<String, K, V>	hashOperations;

	public HttpServletRequest currentRequest() {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attributes != null) {
			return attributes.getRequest();
		}
		return null;
	}

	public String currentUrl() {
		HttpServletRequest request = currentRequest();
		if (request != null) {
			return request.getRequestURI();
		}
		return null;
	}

	public RedisCache(String cacheName, RedisTemplate<String, V> redisTemplate) {
		if (StringUtils.isEmpty(cacheName)) {
			cacheName = DEFAULT_CACHE_NAME;
		}
		if (redisTemplate == null) {
			throw new IllegalArgumentException("redisTemplate can not be null");
		}
		this.hashOperations = redisTemplate.opsForHash();
		this.cacheName = cacheName;
	}

	@Override
	public V get(K key) throws CacheException {
		if (key == null) {
			return null;
		}
		//logger.info(currentUrl() + " RedisCache get() " + key);
		return hashOperations.get(cacheName, key);
	}

	@Override
	public V put(K key, V value) throws CacheException {
		/*if (value instanceof SimpleSession) {
			SimpleSession s = (SimpleSession) value;
			SimplePrincipalCollection c = (SimplePrincipalCollection) s
					.getAttribute("support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
			if (c != null) {
				User primaryPrincipal = (User) c.getPrimaryPrincipal();
				logger.info("cache  put ----> " + primaryPrincipal.getPermissionList().size());
			}
		
		}*/
		V old;
		//logger.info(currentUrl() + " RedisCache put() " + key);
		old = hashOperations.get(cacheName, key);
		hashOperations.put(cacheName, key, value);
		return old;
	}

	@Override
	public V remove(K key) throws CacheException {
		if (key == null) {
			return null;
		}
		V old = hashOperations.get(cacheName, key);
		hashOperations.delete(cacheName, key);
		return old;
	}

	@Override
	public void clear() throws CacheException {
		hashOperations.delete(cacheName);
	}

	@Override
	public int size() {
		Long size = hashOperations.size(cacheName);
		return size.intValue();
	}

	@Override
	public Set<K> keys() {
		return hashOperations.keys(cacheName);
	}

	/**
	 * ICBCSTL-64072  由于Java类serialVersionUID变更造成shiro的session发序列化失败：删除这样的session
	 */
	@Override
	public Collection<V> values() {
		try {
			return hashOperations.values(cacheName);

		} catch (Exception ex) {
			cleanFatalSession();
			return null;
		}
	}

	/**
	 * 清理掉引起错误的session,当获取全部session发生错误的时候
	 */
	private void cleanFatalSession() {
		Set<K> keys = hashOperations.keys(cacheName);
		if (CollectionUtils.isEmpty(keys)) {
			return;
		}
		for (K k : keys) {
			try {
				hashOperations.get(cacheName, k);
			} catch (Exception e) {
				//发生错误，清理掉此session
				hashOperations.delete(cacheName, k);
			}
		}
	}

}